</main>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="../js/bootstrap.bundle.min.js"></script>
            </main>
        </div>
    </div>

    <!-- Toast容器 -->
    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;"></div>

    <script>
        // 创建Toast容器（如果不存在）
        function ensureToastContainer() {
            let container = document.querySelector('.toast-container');
            if (!container) {
                container = document.createElement('div');
                container.className = 'toast-container position-fixed top-0 end-0 p-3';
                container.style.zIndex = '9999';
                document.body.appendChild(container);
            }
            return container;
        }

        // 增强的Toast显示函数
        function showToast(message, type = 'info', duration = 4000) {
            const toastContainer = ensureToastContainer();
            
            const toastId = 'toast-' + Date.now();
            const iconMap = {
                'success': 'bi-check-circle-fill',
                'danger': 'bi-exclamation-triangle-fill', 
                'warning': 'bi-exclamation-circle-fill',
                'info': 'bi-info-circle-fill'
            };
            
            const toastHTML = `
                <div id="${toastId}" class="toast align-items-center text-white bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-icon me-2 ms-3">
                            <i class="bi ${iconMap[type] || 'bi-info-circle'} fs-5"></i>
                        </div>
                        <div class="toast-body flex-grow-1">
                            ${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-3 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                </div>
            `;
            
            toastContainer.insertAdjacentHTML('beforeend', toastHTML);
            
            const toastElement = document.getElementById(toastId);
            const toast = new bootstrap.Toast(toastElement, { 
                delay: duration,
                autohide: duration > 0
            });
            
            toast.show();
            
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
            
            return toast;
        }

        // 美观的确认对话框函数（替换原生confirm）
        function showConfirm(message, confirmCallback, options = {}) {
            const {
                title = '确认操作',
                confirmText = '确认',
                cancelText = '取消',
                confirmButtonClass = 'btn-primary',
                cancelButtonClass = 'btn-secondary',
                size = '' // 'modal-sm', 'modal-lg', 'modal-xl'
            } = options;
            
            const modalId = 'confirmModal-' + Date.now();
            const modalHTML = `
                <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog ${size}">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i class="bi bi-question-circle text-primary me-2"></i>${title}
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="d-flex align-items-start">
                                    <i class="bi bi-exclamation-triangle-fill text-warning fs-4 me-3"></i>
                                    <div class="flex-grow-1">
                                        <p class="mb-0 fs-6">${message}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn ${cancelButtonClass}" data-bs-dismiss="modal">
                                    <i class="bi bi-x-circle me-1"></i>${cancelText}
                                </button>
                                <button type="button" class="btn ${confirmButtonClass}" id="${modalId}-confirm">
                                    <i class="bi bi-check-circle me-1"></i>${confirmText}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            const modalElement = document.getElementById(modalId);
            const modal = new bootstrap.Modal(modalElement);
            
            // 确认按钮事件
            document.getElementById(`${modalId}-confirm`).addEventListener('click', function() {
                modal.hide();
                if (typeof confirmCallback === 'function') {
                    confirmCallback();
                }
            });
            
            // 模态框隐藏后清理
            modalElement.addEventListener('hidden.bs.modal', function() {
                setTimeout(() => {
                    if (this.parentNode) {
                        this.parentNode.removeChild(this);
                    }
                }, 300);
            });
            
            modal.show();
            
            return modal;
        }

        // 危险操作确认对话框
        function showDangerConfirm(message, confirmCallback, options = {}) {
            return showConfirm(message, confirmCallback, {
                title: options.title || '危险操作',
                confirmText: options.confirmText || '确认删除',
                cancelText: options.cancelText || '取消',
                confirmButtonClass: 'btn-danger',
                ...options
            });
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化工具提示
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });

            // 显示闪存消息
            <?php if (isset($_SESSION['flash_message'])): ?>
                showToast('<?php echo addslashes($_SESSION['flash_message']['message']); ?>', '<?php echo $_SESSION['flash_message']['type']; ?>');
                <?php unset($_SESSION['flash_message']); ?>
            <?php endif; ?>
            
            // 自动关闭alert（5秒后）
            const alerts = document.querySelectorAll('.alert:not(.alert-permanent)');
            alerts.forEach(alert => {
                setTimeout(() => {
                    if (alert.parentNode) {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, 5000);
            });
        });

        // 显示加载状态
        function showLoading(button, loadingText = '处理中...') {
            if (!button) return null;
            
            const originalText = button.innerHTML;
            const originalDisabled = button.disabled;
            
            button.disabled = true;
            button.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ${loadingText}`;
            
            return {
                element: button,
                originalText: originalText,
                originalDisabled: originalDisabled
            };
        }
        
        // 隐藏加载状态
        function hideLoading(loadingState) {
            if (!loadingState) return;
            
            const { element, originalText, originalDisabled } = loadingState;
            element.disabled = originalDisabled;
            element.innerHTML = originalText;
        }
        
        // 格式化金额
        function formatAmount(amount) {
            return '¥' + parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
        
        // 格式化时间
        function formatTime(timestamp) {
            if (!timestamp) return '-';
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }
        
        // 复制到剪贴板
        function copyToClipboard(text, successMessage = '已复制到剪贴板') {
            navigator.clipboard.writeText(text).then(() => {
                showToast(successMessage, 'success', 2000);
            }).catch(err => {
                console.error('复制失败:', err);
                showToast('复制失败', 'danger');
            });
        }
        
        // 图片预览
        function previewImage(input, previewId) {
            const preview = document.getElementById(previewId);
            if (!preview) return;
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `<img src="${e.target.result}" class="img-fluid rounded shadow-sm" style="max-height: 200px; cursor: pointer;" onclick="openImageModal('${e.target.result}')">`;
                    preview.style.display = 'block';
                }
                reader.readAsDataURL(input.files[0]);
            } else {
                preview.innerHTML = '';
                preview.style.display = 'none';
            }
        }
        
        // 全局图片模态框
        function openImageModal(imageSrc) {
            const modalId = 'imageModal-' + Date.now();
            const modalHTML = `
                <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-fullscreen">
                        <div class="modal-content bg-dark">
                            <div class="modal-header border-0">
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body d-flex justify-content-center align-items-center">
                                <img src="${imageSrc}" class="img-fluid" style="max-height: 80vh; object-fit: contain;">
                            </div>
                            <div class="modal-footer border-0 justify-content-center">
                                <a href="${imageSrc}" download class="btn btn-primary" target="_blank">
                                    <i class="bi bi-download me-1"></i>下载图片
                                </a>
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                    <i class="bi bi-x-circle me-1"></i>关闭
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            const modalElement = document.getElementById(modalId);
            const modal = new bootstrap.Modal(modalElement);
            
            modalElement.addEventListener('hidden.bs.modal', function() {
                setTimeout(() => {
                    if (this.parentNode) {
                        this.parentNode.removeChild(this);
                    }
                }, 300);
            });
            
            modal.show();
        }
        
        // 侧边栏激活状态
        document.addEventListener('DOMContentLoaded', function() {
            const currentPage = window.location.pathname.split('/').pop() || 'index.php';
            const navLinks = document.querySelectorAll('.sidebar .nav-link');
            
            navLinks.forEach(link => {
                const href = link.getAttribute('href');
                if (href === currentPage || 
                    (currentPage.includes('?') && href === currentPage.split('?')[0]) ||
                    (currentPage === '' && href === 'index.php')) {
                    link.classList.add('active');
                    link.setAttribute('aria-current', 'page');
                } else {
                    link.classList.remove('active');
                    link.removeAttribute('aria-current');
                }
            });
            
            // 页面加载动画
            const mainContent = document.querySelector('main');
            if (mainContent) {
                mainContent.style.opacity = '0';
                mainContent.style.transition = 'opacity 0.3s ease-in-out';
                
                setTimeout(() => {
                    mainContent.style.opacity = '1';
                }, 100);
            }
        });
        
        // 表单提交拦截和加载状态
        document.addEventListener('submit', function(e) {
            const form = e.target;
            const submitBtn = form.querySelector('button[type="submit"], input[type="submit"]');
            
            if (submitBtn && !form.classList.contains('no-loading')) {
                const loadingState = showLoading(submitBtn, '提交中...');
                
                // 防止重复提交
                if (form.dataset.submitting === 'true') {
                    e.preventDefault();
                    return;
                }
                
                form.dataset.submitting = 'true';
                
                // 表单提交完成后恢复按钮状态
                const restoreButton = () => {
                    hideLoading(loadingState);
                    delete form.dataset.submitting;
                };
                
                // 监听表单提交完成（通过fetch或XMLHttpRequest）
                const originalSubmit = form.onsubmit;
                
                form.addEventListener('submit', function submitHandler(ev) {
                    // 如果是AJAX提交，需要在请求完成后调用restoreButton
                    if (form.enctype === 'multipart/form-data' || form.method.toLowerCase() === 'post') {
                        // 对于文件上传或POST请求，设置超时恢复
                        setTimeout(restoreButton, 3000);
                    }
                });
            }
        });
        
        // 全局错误处理
        window.addEventListener('error', function(e) {
            console.error('全局错误:', e.error);
            showToast('发生意外错误，请刷新页面重试', 'danger');
        });
        
        // 网络状态检测
        window.addEventListener('online', function() {
            showToast('网络连接已恢复', 'success', 2000);
        });
        
        window.addEventListener('offline', function() {
            showToast('网络连接已断开，请检查网络', 'warning', 0); // 0表示不自动关闭
        });
    </script>

    <!-- 可选：添加一些美化样式 -->
    <style>
        .toast {
            backdrop-filter: blur(10px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            border: none;
            min-width: 300px;
        }
        
        .toast.bg-success {
            background-color: rgba(25, 135, 84, 0.95) !important;
        }
        
        .toast.bg-danger {
            background-color: rgba(220, 53, 69, 0.95) !important;
        }
        
        .toast.bg-warning {
            background-color: rgba(255, 193, 7, 0.95) !important;
            color: #000 !important;
        }
        
        .toast.bg-warning .btn-close {
            filter: invert(1) grayscale(100%) brightness(200%);
        }
        
        .toast.bg-info {
            background-color: rgba(13, 202, 240, 0.95) !important;
        }
        
        .toast-icon {
            display: flex;
            align-items: center;
        }
        
        /* 确认模态框美化 */
        .modal-content {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            border: none;
        }
        
        /* 加载动画 */
        .spinner-border-sm {
            width: 0.8rem;
            height: 0.8rem;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .toast-container {
                padding: 1rem !important;
            }
            
            .toast {
                min-width: auto;
                width: calc(100vw - 2rem);
            }
        }
    </style>
</body>
</html>